package main

import (
	"log"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
)

type aliDomain struct {
	drr    string
	dtype  string
	dname  string
	dvalue string
	did    string
}

func aliyunCheckDomain(cfg AliyunConfig, domain string) (*alidns.Client, *aliDomain, error) {
	client, err := alidns.NewClientWithAccessKey(cfg.Region, cfg.AccessKeyId, cfg.AccessSecret)
	if err != nil {
		log.Panicln("Client init error : ", err)
	}
	request := alidns.CreateDescribeSubDomainRecordsRequest()
	request.Scheme = "https"

	request.SubDomain = domain

	response, err := client.DescribeSubDomainRecords(request)
	if err != nil {
		log.Println("Response error :", err)
		return nil, nil, err
	}

	byteJson := response.GetHttpContentBytes()
	log.Println("Response json is :", string(byteJson))

	return client, &aliDomain{
		drr:    response.DomainRecords.Record[0].RR,
		dtype:  response.DomainRecords.Record[0].Type,
		dname:  response.DomainRecords.Record[0].DomainName,
		dvalue: response.DomainRecords.Record[0].Value,
		did:    response.DomainRecords.Record[0].RecordId,
	}, nil
}

func (domain *aliDomain) updateDomain(client *alidns.Client, domainValue string) {
	request := alidns.CreateUpdateDomainRecordRequest()
	request.Scheme = "https"

	request.RecordId = domain.did
	request.RR = domain.drr
	request.Type = domain.dtype
	if domain.dvalue == domainValue {
		log.Println("domain ip mush.")
		return
	}
	request.Value = domainValue

	response, err := client.UpdateDomainRecord(request)
	if err != nil {
		log.Println(err.Error())
	} else {
		log.Println("update domain ok :")
	}
	log.Println(response.GetHttpContentString())
}
